<template>
  <v-page
    v-model="refreshing"
    background="#f5f6fa"
    header-background="white"
    footer-background="white"
    :loading="loading"
    :footer="['待支付', '订单已取消', '订单已失效', '待收货'].includes(status)"
    @refresh="refreshHandle"
  >
    <template #header>
      <v-navbar :title="status" native />
    </template>
    <template #default>
      <template v-if="order">
        <view class="order-details-block" style="margin-top: 24rpx">
          <template v-if="actualPaid">
            <view class="address-item" @click="showShipping">
              <v-icon
                size="44rpx"
                src="@/static/icons/order-details-shipping.svg"
              />
              <view class="address-content">
                <view class="address-main">
                  {{ shippingInfoMain }}
                </view>
                <view class="address-sub">
                  {{ shippingInfoSub }}
                </view>
              </view>
              <wd-icon name="arrow-right" size="24rpx" color="#999999" />
            </view>
            <view class="divider" />
          </template>
          <view class="address-item" @click="isShowAddress = true">
            <v-icon
              size="44rpx"
              src="@/static/icons/order-details-address.svg"
            />
            <view class="address-content">
              <view class="address-main">
                {{ addressInfoMain }}
              </view>
              <view class="address-sub">
                {{ addressInfoSub }}
              </view>
            </view>
            <wd-icon name="arrow-right" size="24rpx" color="#999999" />
          </view>
        </view>
        <view class="order-details-block">
          <view class="merchant-info">
            <v-icon size="36rpx" src="@/static/icons/cart-merchant.svg" />
            <view class="merchant-name">
              <view class="name-text">
                {{ order.merchant_name }}
              </view>
            </view>
          </view>
          <template
            v-for="(product, index) in order.order_detail_list"
            :key="product.sku_id"
          >
            <view v-if="index !== 0" class="divider" />
            <order-product
              :product="product"
              :actual-paid="actualPaid"
              show-aftersales
              :tnt-inst-id="tntInstId"
              :scene="scene"
              @click="navigateToProduct(product)"
              @show-comment="showCommentPopup(product)"
              @apply-aftersales="applyAfterSale(product)"
            />
          </template>
        </view>
        <view class="order-details-block">
          <view class="block-info-title">
            价格明细
          </view>
          <view class="block-info-item">
            <view class="label">
              商品总价
            </view>
            <view class="sub-label">
              {{ `共${productCount}件商品` }}
            </view>
            <v-price :price="totalPrice" size="32rpx" color="#333333" />
          </view>
          <template v-if="order.discount_price">
            <view class="block-info-item">
              <view class="label">
                优惠券
              </view>
              <view>
                <v-price
                  :price="-order.discount_price"
                  size="28rpx"
                  color="#ff6d73"
                />
              </view>
            </view>
          </template>
          <view class="block-info-item">
            <view class="label">
              运费
            </view>
            <view>
              {{ shippingText }}
            </view>
          </view>
          <view class="divider" />
          <view class="block-info-item">
            <view class="label">
              {{ payLabel }}
            </view>
            <v-price :price="order.payment" size="32rpx" />
          </view>
        </view>
        <view class="order-details-block">
          <view class="block-info-title">
            订单详情
          </view>
          <view class="block-info-item">
            <view class="label">
              订单编号
            </view>
            <view class="content">
              <view class="sub-text">
                {{ order.id }}
              </view>
              <view class="divider-vertical" />
              <view class="copy-button" @click="copyOrderIdHandle">
                复制
              </view>
            </view>
          </view>
          <view class="block-info-item">
            <view class="label">
              下单时间
            </view>
            <view class="sub-text">
              {{ formateDateTime(order.order_time) }}
            </view>
          </view>
          <view class="block-info-item">
            <view class="label">
              开具发票
            </view>
            <view class="content placeholder">
              本次不开具发票
            </view>
          </view>
          <view class="block-info-item">
            <view class="label">
              订单备注
            </view>
            <view
              class="content"
              :class="{ placeholder: !order.customer_remark }"
              @click="showRemark"
            >
              <view class="remark">
                {{ order.customer_remark || '无备注' }}
              </view>
              <wd-icon
                v-if="order.customer_remark"
                name="arrow-right"
                size="24rpx"
                color="#999999"
              />
            </view>
          </view>
        </view>

        <view class="order-details-block">
          <view class="complaint-container">
            <view class="complaint-text">
              对商品或服务不满意，可点击
            </view>
            <view class="complaint-button" @click="navigateToComplaint">
              投诉反馈
            </view>
          </view>
        </view>
      </template>
    </template>
    <template #footer>
      <view class="footer">
        <template v-if="status === '待支付'">
          <v-button
            :custom-style="{
              height: '78rpx',
              padding: '0 28rpx',
              minWidth: '168rpx',
              borderColor: 'transparent',
              marginRight: 'auto'
            }"
            type="text"
            @click="cancelOrder"
          >
            取消订单
          </v-button>
          <v-button
            :custom-style="{
              height: '78rpx',
              padding: '0 28rpx',
              minWidth: '168rpx'
            }"
            type="primary"
            @click="payOrder"
          >
            去支付
          </v-button>
        </template>
        <template
          v-else-if="status === '订单已取消' || status === '订单已失效'"
        >
          <v-button
            :custom-style="{
              height: '78rpx',
              padding: '0 28rpx',
              minWidth: '168rpx'
            }"
            type="plain"
            @click="deleteOrder"
          >
            删除订单
          </v-button>
        </template>
        <template v-if="status === '待收货'">
          <v-button
            :custom-style="{
              height: '78rpx',
              padding: '0 28rpx',
              minWidth: '168rpx'
            }"
            type="primary"
            @click="confirmOrder"
          >
            确认收货
          </v-button>
        </template>
      </view>
    </template>
    <template #popup>
      <order-details-shipping-popup
        v-if="order"
        v-model:show="isShowShipping"
        :order="order"
      />
      <order-details-address-popup
        v-if="order"
        v-model:show="isShowAddress"
        :order="order"
      />
      <order-details-aftersales-apply-popup
        v-if="order"
        v-model:show="isShowAftersalesPoppover"
        :order="order"
        :product="aftersalesProduct"
      />
      <order-details-comment-apply-popup
        v-if="commentProduct"
        v-model:show="isShowCommentPopup"
        :product="commentProduct"
      />
      <m-textarea-popup
        v-if="order?.customer_remark"
        v-model:show="isShowRemarkPopup"
        :model-value="order.customer_remark"
        title="订单备注"
      />
    </template>
  </v-page>
</template>

<script setup lang="ts">
import OrderProduct from './modules/order-product.vue';
import OrderDetailsShippingPopup from './modules/order-details-shipping-popup.vue';
import OrderDetailsAftersalesApplyPopup from './modules/order-details-aftersales-apply-popup.vue';
import OrderDetailsAddressPopup from './modules/order-details-address-popup.vue';
import OrderDetailsCommentApplyPopup from './modules/order-details-comment-apply-popup.vue';
import usePayment from '@/composables/use-payment';
import useSafeNavigateBack from '@/composables/use-safe-navigate-back';
import { formateDateTime } from '@/utils/formater';

const { safeNavigateBack } = useSafeNavigateBack();

const orderId = ref('');
const order = ref<OrderVO>();
const merchant = ref<MerchantVO>();
const tntInstId = computed(() => {
  if (merchant.value?.customer_service_status !== 'ENABLED') return undefined;
  return merchant.value?.customer_service_setting?.tenant_id;
});
const scene = computed(() => {
  if (merchant.value?.customer_service_status !== 'ENABLED') return undefined;
  return merchant.value?.customer_service_setting?.chat_window_id;
});
const getOrderDetails = async () => {
  const response = await $api.getOrderQueryIdDetail(orderId.value);
  switch (response.__error) {
    case undefined:
      order.value = response.data;
      break;
  }
};
const getMerchant = async () => {
  if (!order.value?.merchant_id) return;
  const response = await $api.getMerchantId(order.value.merchant_id);
  switch (response.__error) {
    case undefined:
      merchant.value = response.data;
      break;
  }
};

const isShowShipping = ref(false);
const showShipping = () => {
  if (!order.value?.express) return;
  isShowShipping.value = true;
};

const isShowAddress = ref(false);
const isShowRemarkPopup = ref(false);
const showRemark = () => {
  if (!order.value?.customer_remark) return;
  isShowRemarkPopup.value = true;
};

const status = computed(() => {
  if (!order.value) return '';
  switch (true) {
    case order.value.status === 'PLACED_AN_ORDER':
      return '待支付';
    case order.value.status === 'CANCEL':
      return '订单已取消';
    case order.value.status === 'EXPIRED':
      return '订单已失效';
    case order.value.status === 'PAID':
      return '待发货';
    case order.value.status === 'SHIPPED':
      return '待收货';
    case order.value.status === 'SIGNED_FOR':
      return '已收货';
    case order.value.status === 'COMPLETED':
      return '已完成';
    case order.value.status === 'PART_REFUND':
      return '部分退款';
    case order.value.status === 'ALL_REFUND':
      return '已退款';
    default:
      return '';
  }
});

/** 复合判断 需要支付，支付状态 */
const actualPaid = computed(() => {
  if (!order.value) return false;
  // 不需要支付
  if (!order.value.payable) return true;
  return order.value.pay_status !== 'UNPAID';
});

const shippingInfoMain = computed(() => {
  if (!order.value) return '';
  if (status.value === '已收货') return '已完成';
  const list = order.value.express?.detail_list ?? [];
  const lastDetail = list[list.length - 1];
  if (!lastDetail) return '商家待发货';
  return lastDetail.status;
});
const shippingInfoSub = computed(() => {
  if (!order.value) return '';
  if (status.value === '已收货') return '您的快递已成功签收';
  const list = order.value.express?.detail_list ?? [];
  const lastDetail = list[list.length - 1];
  if (!lastDetail) return '您的订单正在处理中，请耐心等候';
  return lastDetail.context;
});

const addressInfoMain = computed(() => {
  const recipientInfo = order.value?.recipient_info;
  if (!recipientInfo) return '';
  const info = recipientInfo as unknown as RecipientInfo;
  return `${info.prov}${info.city}${info.city}${info.area} ${info.address}`;
});

const addressInfoSub = computed(() => {
  const recipientInfo = order.value?.recipient_info;
  if (!recipientInfo) return '';
  const info = recipientInfo as unknown as RecipientInfo;
  return `${info.recipient} ${info.mobile}`;
});

const productCount = computed(() => {
  if (!order.value) return 0;
  return order.value.order_detail_list.reduce((acc, cur) => {
    return acc + cur.quantity;
  }, 0);
});

const totalPrice = computed(() => {
  if (!order.value) return 0;
  return order.value.order_detail_list.reduce((acc, cur) => {
    return acc + cur.quantity * (cur.sell_price ?? 0);
  }, 0);
});

const shippingText = computed(() => {
  if (!order.value) return '-';
  const fee = order.value.shipping_fee;
  if (fee === 0) return '包邮';
  return `¥${fee.toFixed(2)}`;
});

const payLabel = computed(() => {
  if (!order.value) return '';
  switch (order.value.pay_status) {
    case 'UNPAID':
      return '应付款';
    case 'PAID':
      return '已付款';
    default:
      return '';
  }
});

const loading = ref(true);
onLoad((query) => {
  orderId.value = query?.id as string;
});
onShow(async () => {
  // loading.value = true;
  await getOrderDetails();
  await getMerchant();
  loading.value = false;
  if (!order.value) safeNavigateBack();
});

const refreshing = ref(false);
const refreshHandle = async () => {
  refreshing.value = true;
  await getOrderDetails();
  await getMerchant();
  refreshing.value = false;
};

const cancelOrder = async () => {
  if (!order.value) return;
  const result = await uni.showModal({
    title: '提示',
    content: '确定取消订单吗？'
  });
  if (!result.confirm) return;
  uni.showLoading({ mask: true });
  const response = await $api.getOrderSubmitMergeNoCancel(order.value.merge_no);
  uni.hideLoading();
  switch (response.__error) {
    case undefined:
      uni.showToast({ title: '取消订单成功', icon: 'none' });
      uni.$emit('refresh-order-list');
      getOrderDetails();
      break;
  }
};
const payOrder = async () => {
  if (!order.value) return;
  const { payOrder } = usePayment();
  let result = false;
  // #ifdef MP-ALIPAY
  if (order.value.pay_product === 'MERGE_PAY') {
    const tradeNo = order.value.out_merge_no ?? order.value.out_trade_no;
    result = await payOrder(tradeNo, { bizType: 'merge_order' });
  } else {
    result = await payOrder(order.value.out_trade_no);
  }
  // #endif
  // #ifdef MP-WEIXIN
  const response = await $api.getOrderRestateMergeNoPayment(
    order.value.merge_no
  );
  switch (response.__error) {
    case undefined:
      result = await payOrder({
        timeStamp: response.data.timeStamp,
        nonceStr: response.data.nonceStr,
        package: response.data.packageVal,
        signType: response.data.signType,
        paySign: response.data.paySign
      });
      break;
  }
  // #endif
  if (result) uni.$emit('refresh-order-list');
};
const deleteOrder = async () => {
  if (!order.value) return;
  const result = await uni.showModal({
    title: '提示',
    content: '确定删除订单吗？'
  });
  if (!result.confirm) return;
  uni.showLoading({ mask: true });
  const response = await $api.deleteOrderQueryId(order.value.id);
  uni.hideLoading();
  switch (response.__error) {
    case undefined:
      uni.showToast({ title: '删除订单成功', icon: 'none' });
      uni.$emit('refresh-order-list');
      safeNavigateBack();
      break;
  }
};
const confirmOrder = async () => {
  if (!order.value) return;
  const result = await uni.showModal({
    title: '提示',
    content: '确定确认收货吗？'
  });
  if (!result.confirm) return;
  uni.showLoading({ mask: true });
  const response = await $api.getOrderSubmitIdConfirm(order.value.id);
  uni.hideLoading();
  switch (response.__error) {
    case undefined:
      uni.showToast({ title: '确认收货成功', icon: 'none' });
      uni.$emit('refresh-order-list');
      getOrderDetails();
      break;
  }
};

const copyOrderIdHandle = () => {
  if (!order.value?.id) return;
  uni.setClipboardData({
    data: order.value.id,
    success: () => {
      uni.showToast({ title: '复制成功', icon: 'none' });
    }
  });
};

const isShowAftersalesPoppover = ref(false);
const aftersalesProduct = ref<OrderDetailVO>();
const applyAfterSale = async (product: OrderDetailVO) => {
  if (product.basic_status) {
    const result = await uni.showModal({
      title: '提示',
      content: '您是否想继续申请售后？'
    });
    if (!result.confirm) return;
  }
  aftersalesProduct.value = product;
  isShowAftersalesPoppover.value = true;
};

const commentProduct = ref<OrderDetailVO>();
const isShowCommentPopup = ref(false);
const showCommentPopup = (product: OrderDetailVO) => {
  commentProduct.value = product;
  isShowCommentPopup.value = true;
};

const navigateToProduct = (product: OrderDetailVO) => {
  uni.navigateTo({
    url: `/pages/product/product-details?id=${product.spu_id}`
  });
};
const navigateToComplaint = () => {
  const pageStore = $store.page();
  pageStore.setParameters({ order: order.value });
  uni.navigateTo({ url: '/pages/complaint/complaint-type-select' });
};
</script>

<style lang="scss" scoped>
.order-details-block {
  margin: 0 24rpx 24rpx;
  padding: 20rpx 24rpx;
  border-radius: 16rpx;
  background-color: white;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  gap: 12rpx;
  .address-item {
    display: flex;
    align-items: center;
    gap: 24rpx;
    .address-content {
      flex: 1;
      min-width: 0;
      .address-main {
        font-weight: bold;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        word-break: break-all;
        margin-bottom: 8rpx;
      }
      .address-sub {
        color: #999999;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        word-break: break-all;
        display: inline-flex;
        gap: 0 8rpx;
      }
    }
  }

  .merchant-info {
    height: 40rpx;
    display: flex;
    align-items: center;
    gap: 16rpx;
    .merchant-name {
      flex: 1;
      min-width: 0;
      display: flex;
      align-items: center;
      .name-text {
        font-size: 28rpx;
        font-weight: bold;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        word-break: break-all;
      }
    }
  }

  .divider {
    height: 1px;
    background-color: #eeeeee;
  }
  .divider-vertical {
    width: 1px;
    height: 26rpx;
    background-color: #eeeeee;
  }

  .block-info-title {
    font-weight: bold;
    font-size: 30rpx;
  }

  .block-info-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 24rpx;
    min-height: 60rpx;
    .label {
      flex-shrink: 0;
    }
    .sub-label {
      color: #999999;
      font-weight: 300;
      flex: 1;
      min-width: 0;
    }
    .content {
      flex: 1;
      min-width: 0;
      display: flex;
      align-items: center;
      justify-content: flex-end;
      gap: 12rpx;
      &.placeholder {
        color: #999999;
        font-weight: 300;
      }
      .remark {
        flex: 1;
        min-width: 0;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        word-break: break-all;
        text-align: right;
        &.placeholder {
          color: #999999;
          font-weight: 300;
        }
      }
    }
    .sub-text {
      color: #999999;
    }
  }

  .copy-button {
    padding: 4rpx 8rpx;
  }

  .complaint-container {
    display: flex;
    align-items: center;
    justify-content: center;
    line-height: 60rpx;
    gap: 16rpx;
    .complaint-text {
      color: #999999;
    }
    .complaint-button {
      color: #ff6d73;
      text-decoration: underline;
    }
  }
}
.footer {
  display: flex;
  justify-content: flex-end;
  gap: 30rpx;
  padding: 12rpx 24rpx 0;
}
</style>
